# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# 作者：'yu.qian'
# 公司网址： http://www.dtcloud360.com/
# 日期：2023/2/23 15:01
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
import Config
import modbus_tk.modbus_tcp as mt

MODULE_WAIT_TIME = 5  # 原来是100


class ModbusMasterTcpServer(object):  # modbus
    def __init__(self, host, port, slave):
        """
        :param host: 服务器地址
        :param port: 端口
        :param slave: 从设备的标识符
        """
        self.host = host
        if type(port) == int:
            self.port = port
        else:
            self.port = int(port)

        if type(slave) == int:
            self.slave = slave
        else:
            self.slave = int(slave)

        self.master = mt.TcpMaster(host=self.host, port=self.port)

    def read_inputs(self, function_code, starting_address, quantity_of_x=1):
        # 连接远程服务器
        result = None
        try:
            self.master.set_timeout(MODULE_WAIT_TIME)  # 超时设定
            # 执行读取指令
            result = self.master.execute(slave=self.slave, function_code=function_code,
                                         starting_address=starting_address,
                                         quantity_of_x=quantity_of_x)
            return result
        except Exception as e:
            print('异常:', e)
            return result

    def read_discrete_inputs(self, function_code, starting_address, quantity_of_x=1):
        '''读取离散输入'''
        result = None
        try:
            self.master.set_timeout(MODULE_WAIT_TIME)  # 超时设定
            # 执行读取指令
            result = self.master.execute(slave=self.slave, function_code=function_code,
                                         starting_address=starting_address,
                                         quantity_of_x=quantity_of_x)
            return result
        except Exception as e:
            print('异常:', e)
            return result

    def read_input_regisiters(self, function_code, starting_address, quantity_of_x=1):
        '''读入输入寄存器'''
        result = None
        try:
            self.master.set_timeout(MODULE_WAIT_TIME)
            result = self.master.execute(slave=self.slave, function_code=function_code,
                                         starting_address=starting_address,
                                         quantity_of_x=quantity_of_x)
            return result
        except Exception as e:

            print('异常:', e)
            return result

    def read_holding_regisiters(self, function_code, starting_address, quantity_of_x=1):
        '''读入保持寄存器'''

        result = None
        try:
            self.master.set_timeout(MODULE_WAIT_TIME)

            result = self.master.execute(slave=self.slave, function_code=function_code,
                                         starting_address=starting_address,
                                         quantity_of_x=quantity_of_x)
            print("寄存器地址{}:读取的数据{}".format(starting_address, result))

            return result
        except Exception as e:

            print('异常:', e)
            return result

    def write_single_regisiters(self, function_code, starting_address, output_value):
        '''写入寄存器值'''
        result = None
        try:
            self.master.set_timeout(MODULE_WAIT_TIME)
            result = self.master.execute(slave=self.slave, function_code=function_code,
                                         starting_address=starting_address,
                                         output_value=output_value)
            print(type(result), 'write_single_regisiters')
            return result
        except Exception as e:

            print('异常:', e)
            return result

    def read_error_holding_regisiters(self, function_code, starting_address, quantity_of_x=1):
        "读取报警地址数据（功能码01）"
        result = ""
        try:
            self.master.set_timeout(MODULE_WAIT_TIME)
            result = self.master.execute(slave=self.slave, function_code=function_code,
                                         starting_address=starting_address,
                                         quantity_of_x=quantity_of_x)
            return result
        except Exception as e:
            print('异常:', e)
            return result

modbus = ModbusMasterTcpServer(host='10.3.36.201', port=1502, slave=1)


if __name__ == '__main__':
    # a = [49, 50, 51, 52, 53]
    # for i in a:
    # 读取保持寄存器
    result_1 = modbus.read_holding_regisiters(function_code=4, starting_address=30,quantity_of_x=6)
    print(result_1)

    # result2 = modbus.read_holding_regisiters(function_code=4, starting_address=54, quantity_of_x=4)
    # print(f"\033[35m --- {result2} ---\033[0m")
    # result3 = modbus.read_holding_regisiters(function_code=4, starting_address=59, quantity_of_x=4)
    # result4 = modbus.read_holding_regisiters(function_code=4, starting_address=64, quantity_of_x=4)
    # b = ['开关', '模式', '风速', '温度', '读房间温度']

    # print(f"\033[35m --- {dict(**zip(result))} ---\033[0m")
    # print(dict(zip(b, result)))
    # print(dict(zip(b, result2)))
    # print(dict(zip(b, result3)))
    # print(dict(zip(b, result4)))
    # print(f"\033[35m --- {result2} ---\033[0m")
    # print(f"\033[35m --- {result3} ---\033[0m")

    # result = modbus.write_single_regisiters(function_code=6, starting_address=65, output_value=8)
    # print(f"\033[35m --- {result} ---\033[0m")

    print(f"\033[35m --- {result_1[0]} ---\033[0m")
